package com.alibaba.citrus.cr.unified.inventory.facade.service;

import com.alibaba.citrus.cr.unified.inventory.repository.ConsignmentOrderRepository;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crunifiedinventory.consignmentorderquery.service.ConsignmentOrderQueryService;
import com.epoch.app.crunifiedinventory.model.dto.ConsignmentOrderQueryRequest;
import com.epoch.app.crunifiedinventory.sdo.ConsignmentOrderLineSearchResponse;
import com.epoch.app.crunifiedinventory.sdo.ConsignmentOrderSDO;
import com.epoch.app.crunifiedinventory.sdo.ConsignmentOrderSearchResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: qianlei
 * @create: 2021/11/10 21:39
 */
@Component
@Primary
public class ConsignmentOrderQueryServiceImpl implements ConsignmentOrderQueryService {
    @Resource
    private ConsignmentOrderRepository consignmentOrderRepository;

    @Override
    public Result<ConsignmentOrderSDO> querySingleBySale(ConsignmentOrderQueryRequest consignmentOrderQueryRequest){
        ConsignmentOrderSDO query = consignmentOrderRepository.queryByOuterSaleNo(consignmentOrderQueryRequest.getOuterSalesOrderId());
        return Result.success(query);
    }

    @Override
    public Result<ConsignmentOrderSDO> querySingle(ConsignmentOrderQueryRequest consignmentOrderQueryRequest){

        ConsignmentOrderSDO order = consignmentOrderRepository.query(consignmentOrderQueryRequest.getOuterDeliveryOrderId());
        if(order != null && !Objects.equals(order.getStatus(),0)){
            return Result.success(order);
        }
        return Result.success(null);
    }

    @Override
    public Result<ConsignmentOrderSearchResponse> searchOrder(ConsignmentOrderQueryRequest consignmentOrderQueryRequest) {
        ConsignmentOrderSDO order = consignmentOrderRepository.query(consignmentOrderQueryRequest.getOuterDeliveryOrderId());
        if(order != null && !Objects.equals(order.getStatus(),0)){
            ConsignmentOrderSearchResponse response = new ConsignmentOrderSearchResponse();
            BeanUtils.copyProperties(order,response);
            response.setConsignmentOrderLine(order.getConsignmentOrderLineSDOS().stream().map(lineSdo->{
                ConsignmentOrderLineSearchResponse lineRes = new ConsignmentOrderLineSearchResponse();
                BeanUtils.copyProperties(lineSdo,lineRes);
                return lineRes;
            }).collect(Collectors.toList()));
            return Result.success(response);
        }
        return Result.success(null);
    }
}
